﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DreamHome.Models;
using DreamHome.Repositories;
using System.IO;

namespace DreamHome.Repositories
{
    class BranchRepository
    {
        private readonly String _filePath;
        private readonly String _dateFormat;
        private readonly String _fileDelimeter;

        public BranchRepository(string filePath, string dateFormat, string fileDelimeter)
        {
            if (String.IsNullOrWhiteSpace(filePath))
                throw new ArgumentNullException("filePathForBranch");

            if (String.IsNullOrWhiteSpace(dateFormat))
                throw new ArgumentNullException("dateFormatForBranch");

            if (String.IsNullOrWhiteSpace(fileDelimeter))
                throw new ArgumentNullException("fileDelimeterForBranch");

            _filePath = filePath;
            _dateFormat = dateFormat;
            try
            {
                int number = Convert.ToInt32(fileDelimeter);
            }
            catch (FormatException e)
            {
                _fileDelimeter = fileDelimeter;
                return;
            }
            char ch = System.Convert.ToChar(System.Convert.ToUInt32(fileDelimeter));
            _fileDelimeter = new String(ch, 1);                    
        }

        public void CreateBranch(Branch newBranch)
        {
            String PrepaiedBranchRecord = newBranch.branchNo + _fileDelimeter + newBranch.street + _fileDelimeter +
                newBranch.city + _fileDelimeter + newBranch.postcode + _fileDelimeter + newBranch.IsValid + _fileDelimeter;
            File.AppendAllText(_filePath, PrepaiedBranchRecord + "\r\n");
        }

        #region SELECT * FROM Branch;
        public List<Branch> SelectAllFromBranch(List<Branch> allFromBranch)
        {
            char[] seps = { ';' };

            foreach (string record in File.ReadAllLines(_filePath))
            {
                    Branch tmpBranchRecord = new Branch();
          //          Console.WriteLine("record: {0}", record);
                    string[] parts = record.Split(seps);        // deviding of string on parts
                    tmpBranchRecord.branchNo = parts[0];
                    tmpBranchRecord.street = parts[1];
                    tmpBranchRecord.city = parts[2];
                    tmpBranchRecord.postcode = parts[3];
                    tmpBranchRecord.IsValid = parts[4];
         //           Console.WriteLine("branchNo: {0}, street: {1}, city: {2}, postcode: {3}, is valid: {4}", tmpBranchRecord.branchNo, tmpBranchRecord.street, tmpBranchRecord.city, tmpBranchRecord.postcode, tmpBranchRecord.IsValid);

                    allFromBranch.Add(tmpBranchRecord);
            }
            return allFromBranch;
        }
        #endregion

    }

}
